from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.postgres import get_session
from app.models import WeiboNote, XhsNote, DouyinAweme, KuaishouVideo, BilibiliVideo, TiebaNote, ZhihuContent
from app.schemas.social_content import ContentQuery, ContentItem, ContentList


router = APIRouter(prefix="/social/contents", tags=["social-contents"])


@router.post("/query", response_model=ContentList)
async def query_contents(payload: ContentQuery, session: AsyncSession = Depends(get_session)):
    items = []
    plats = set([p for p in (payload.platforms or [])])
    if not plats or 'weibo' in plats:
        q = select(WeiboNote)
        if payload.topic_code:
            q = q.where(WeiboNote.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q = q.where(WeiboNote.published_at >= payload.time_start).where(WeiboNote.published_at <= payload.time_end)
        result = await session.execute(q)
        for x in result.scalars().all():
            items.append(ContentItem(platform='weibo', content_id=str(x.note_id or ''), author=x.nickname or None, title=None, text=x.content or None, url=x.note_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'xhs' in plats:
        q2 = select(XhsNote)
        if payload.topic_code:
            q2 = q2.where(XhsNote.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q2 = q2.where(XhsNote.published_at >= payload.time_start).where(XhsNote.published_at <= payload.time_end)
        result2 = await session.execute(q2)
        for x in result2.scalars().all():
            items.append(ContentItem(platform='xhs', content_id=str(x.note_id or ''), author=x.nickname or None, title=x.title or None, text=x.desc or None, url=x.note_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'douyin' in plats:
        q3 = select(DouyinAweme)
        if payload.topic_code:
            q3 = q3.where(DouyinAweme.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q3 = q3.where(DouyinAweme.published_at >= payload.time_start).where(DouyinAweme.published_at <= payload.time_end)
        result3 = await session.execute(q3)
        for x in result3.scalars().all():
            items.append(ContentItem(platform='douyin', content_id=str(x.aweme_id or ''), author=x.nickname or None, title=x.title or None, text=x.desc or None, url=x.aweme_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'kuaishou' in plats:
        q4 = select(KuaishouVideo)
        if payload.topic_code:
            q4 = q4.where(KuaishouVideo.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q4 = q4.where(KuaishouVideo.published_at >= payload.time_start).where(KuaishouVideo.published_at <= payload.time_end)
        result4 = await session.execute(q4)
        for x in result4.scalars().all():
            items.append(ContentItem(platform='kuaishou', content_id=str(x.video_id or ''), author=x.nickname or None, title=x.title or None, text=x.desc or None, url=x.video_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'bilibili' in plats:
        q5 = select(BilibiliVideo)
        if payload.topic_code:
            q5 = q5.where(BilibiliVideo.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q5 = q5.where(BilibiliVideo.published_at >= payload.time_start).where(BilibiliVideo.published_at <= payload.time_end)
        result5 = await session.execute(q5)
        for x in result5.scalars().all():
            items.append(ContentItem(platform='bilibili', content_id=str(x.video_id or ''), author=x.nickname or None, title=x.title or None, text=x.desc or None, url=x.video_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'tieba' in plats:
        q6 = select(TiebaNote)
        if payload.topic_code:
            q6 = q6.where(TiebaNote.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q6 = q6.where(TiebaNote.published_at >= payload.time_start).where(TiebaNote.published_at <= payload.time_end)
        result6 = await session.execute(q6)
        for x in result6.scalars().all():
            items.append(ContentItem(platform='tieba', content_id=str(x.note_id or ''), author=x.user_nickname or None, title=x.title or None, text=x.desc or None, url=x.note_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    if not plats or 'zhihu' in plats:
        q7 = select(ZhihuContent)
        if payload.topic_code:
            q7 = q7.where(ZhihuContent.topic_code == payload.topic_code)
        if not payload.ignore_time_filter and payload.time_start and payload.time_end:
            q7 = q7.where(ZhihuContent.published_at >= payload.time_start).where(ZhihuContent.published_at <= payload.time_end)
        result7 = await session.execute(q7)
        for x in result7.scalars().all():
            items.append(ContentItem(platform='zhihu', content_id=str(x.content_id or ''), author=x.user_nickname or None, title=x.title or None, text=x.desc or None, url=x.content_url or None, published_at=str(x.published_at) if x.published_at else None, metrics=None))
    return ContentList(items=items)
